package com.isoftstone.studentregistration.service.impl;

import cn.hutool.core.io.IoUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.isoftstone.studentregistration.mapper.UserMapper;
import com.isoftstone.studentregistration.pojo.Users;
import com.isoftstone.studentregistration.service.UserService;
import com.isoftstone.studentregistration.util.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Date;
import java.util.List;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;
    //添加用户
    @Override
    public Result<?> insertUser(Users user) {
        // 判断手机号是否已注册
        Users users = userMapper.queryUserByPhone(user.getPhone());
        if (users == null) {
            //系统生成时间
            user.setCreateDate(new Date());
            //将密码进行加密
            user.setPassword(new String(SecureUtil.md5(user.getPassword())));
            int insert = userMapper.insertUser(user);
            if (insert > 0) {
                return Result.success("添加成功");
            }
            return Result.error("添加失败");
        }
        return Result.error("该手机号已注册");
    }
    //修改用户
    @Override
    public Result<?> updateUser(Users user) {
        user.setUpdateDate(new Date());
        user.setPassword(new String(SecureUtil.md5(user.getPassword())));
        int update = userMapper.updateUser(user);
        if (update > 0) {
            return Result.success("修改成功");
        }
        return Result.error("修改失败");
    }
    //删除用户
    @Override
    public Result<?> deleteUser(Integer id) {
        int delete = userMapper.deleteUser(id);
        if (delete > 0) {
            return Result.success("删除成功");
        }
        return Result.error("删除失败");
    }

    //批量删除
    @Override
    public int batchDeleteUser(List<Integer> ids) {
        if (ids == null || ids.isEmpty()) {
            return 0;
        }
        return userMapper.batchDeleteUser(ids);
    }
    //查询所有用户
    @Override
    public Page<Users> queryAllUsers(Integer currentPage, Integer pageSize) {
        Page<Users> page= PageHelper.startPage(currentPage, pageSize);//PageHelper.startPage(currentPage, pageSize);之后按Alt+Enter键升
        userMapper.queryAllUsers();
        return page;
    }

    @Override
    public Users queryUserById(Integer id) {
        return userMapper.queryUserById(id);
    }
    @Override
    public Result<?> login(String phone, String password) {
        System.out.println("用户登录：" + phone + " " + password);
        Users user = userMapper.login(phone, password);
        System.out.println("用户登录：" + user);
        return user == null ? Result.error("账号或密码错误") : Result.success(user);
    }

    @Override
    public void exportExcel(HttpServletResponse response) throws IOException {
        //1.查询所有用户信息
        List< Users> users = userMapper.queryAllUsers();
        //通过工具类创建writer，默认创建xls格式
        ExcelWriter writer = ExcelUtil.getWriter(true);
        //3.将list数据写入Excel
        writer.write(users, true);
        //4.设置浏览器响应格式
        response.setContentType("application/vnd.ms-excel;charset=utf-8");
        //5.设置浏览器响应头
        String fileName = URLEncoder.encode("用户信息", "UTF-8");
        response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ".xlsx");
        //获取输出流
        ServletOutputStream out = response.getOutputStream();
        writer.flush(out, true);//刷新缓冲区
        writer.close();//关闭writer 释放资源writer.flush(out, true);与writer.close（）顺序不能搞错

        IoUtil.close(out);
    }



}
